﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TowerDefender.Entities;
using System.Xml;
using System.Xml.Linq;

namespace TowerDefender.Data
{
    public class FileManager
    {
        /// <summary>
        /// Create a Map object from an xml file
        /// </summary>
        /// <param name="path">The file path</param>
        /// <returns></returns>
        public static Map LoadMap(string path)
        {
            Map map = null;


            XDocument doc = XDocument.Load(path);
            var steps = from step in doc.Descendants("Cell")
                        select new
                        {
                            X = step.Attribute("X"),
                            Y = step.Attribute("Y")
                        };

            MapPath mapPath = new MapPath();

            foreach (var step in steps)
            {
                int X = int.Parse(step.X.Value);
                int Y = int.Parse(step.Y.Value);
                mapPath.AddStep(X, Y);
            }

            var mapSettings = (from m in doc.Descendants("Map")
                               select new
                               {
                                   width = int.Parse(m.Attribute("width").Value),
                                   length = int.Parse(m.Attribute("length").Value)
                               }).First();

            map = new Map(mapSettings.width, mapSettings.length, mapPath);

            return map;
        }
    }
}
